package com.yt.app.api.action;

import com.yt.app.api.action.base.BaseAction;
import com.yt.app.api.util.Config;
import com.yt.app.api.vo.*;
import com.yt.app.core.interfaces.UserOrderDetailService;
import com.yt.app.core.interfaces.UserOrderService;
import com.yt.app.core.model.UserOrder;
import com.yt.app.core.model.UserOrderDetail;
import com.yt.app.core.utils.Constant;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@Api(tags = "10.我的订单")
@RequestMapping("/my/order")
public class MyOrderController extends BaseAction{
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private UserOrderDetailService userOrderDetailService;

    @ApiOperation(value="我的订单列表", httpMethod = "GET")
    @RequestMapping("/list")
    @ApiResponses(value = {@ApiResponse(code = 200,message = "订单信息", response = UserOrderListVo.class)})
    public @ResponseBody  Object getOrderList(
            @ApiParam("订单状态,-1：为全部,0:未支付,1:已支付,2:已取消,3.已退款") @RequestParam(value = "orderStatus", required = false, defaultValue = "0") String orderStatus,
            @ApiParam("上一页最后一个记录的ID") @RequestParam(value = "lastId", required = false, defaultValue = "0") Long lastId,
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        QueryFilter filter = new DynamicSQLFilterImpl();
        filter.addFilter("Q_uid_L_EQ", String.valueOf(uid));
        if(!"-1".equals(orderStatus)) {
            filter.addFilter("Q_orderStatus_S_EQ", orderStatus);
        }
        if(lastId > 0){
            filter.addFilter("Q_id_L_LT", String.valueOf(lastId));
        }

        filter.setSortField("id", true);

        List<UserOrder> userOrderList = userOrderService.find(filter);
        List<UserOrderListVo> voList = new ArrayList<UserOrderListVo>();

        if(userOrderList != null && !userOrderList.isEmpty()) {
            for(UserOrder userOrder : userOrderList) {
                UserOrderListVo vo = new UserOrderListVo();
                vo.setId(userOrder.getId());
                vo.setOrderNo(userOrder.getOrderNo());
                vo.setAmount(userOrder.getAmount());
                vo.setOrderStatus(userOrder.getOrderStatus());
                vo.setOrderTime(userOrder.getOrderTime());
                List<UserOrderDetail> detailList = userOrderDetailService.getByOrderId(userOrder.getId());
                for(UserOrderDetail detail : detailList){
                    vo.setInstitutionId(detail.getInstitutionId());
                    vo.setInstitutionName(detail.getInstitutionName());
                    vo.setProductId(detail.getProductId());
                    vo.setProductName(detail.getProductName());
                    vo.setProductPrice(detail.getSalePrice());
                    vo.setProductImage(detail.getImageFile());
                    vo.setProductCount(detail.getProductCount());
                    break;
                }
                voList.add(vo);
                lastId = userOrder.getId();
            }
        }else{
            lastId = -1L;
        }
        msgBean.put("lastId", lastId);
        msgBean.put("userOrders", voList);

        return msgBean.returnMsg();
    }

    @ApiOperation(value="订单详情", httpMethod = "GET")
    @RequestMapping("/detail")
    @ApiResponses(value = {@ApiResponse(code = 200,message = "订单信息", response = UserOrderVo.class)})
    public @ResponseBody  Object getOrderDetail(
            @ApiParam(value = "订单号", required = true) @RequestParam(value = "orderNo", required = false, defaultValue = "") String orderNo,
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);

        UserOrder userOrder = userOrderService.getByOrderNo(orderNo);
        if(!userOrder.getUid().equals(uid)){
            return msgBean.failure("非法操作").returnMsg();
        }
        UserOrderVo vo = new UserOrderVo();
        vo.setUserOrder(userOrder);
        List<UserOrderDetail> detailList = userOrderDetailService.getByOrderId(userOrder.getId());
        List<UserOrderDetailVo> detailVoList = new ArrayList<UserOrderDetailVo>();
        UserOrderDetailVo detailVo = null;
        long lastProId = 0L;
        for(UserOrderDetail detail : detailList){
            if(lastProId != detail.getProductId()){
                lastProId = detail.getProductId();
                detailVo = new UserOrderDetailVo();
                detailVoList.add(detailVo);

                detailVo.setId(detail.getId());
                detailVo.setInstitutionId(detail.getInstitutionId());
                detailVo.setInstitutionName(detail.getInstitutionName());
                detailVo.setProductId(detail.getProductId());
                detailVo.setProductName(detail.getProductName());
                detailVo.setSalePrice(detail.getSalePrice());
                detailVo.setImageFile(detail.getImageFile());
            }
            CardVo cardVo = new CardVo();
            cardVo.setCardNo(detail.getCardNo());
            cardVo.setCardPassword(detail.getCardPassword());
            cardVo.setStatus(detail.getLeftCount() > 0?0:1);
            detailVo.addCard(cardVo);
        }
        vo.setUserOrderDetails(detailVoList);
        ExpressVo expressVo = new ExpressVo();
        expressVo.setExpressNo("XXXXXXXXX");
        expressVo.setExpressName("申通快递");
        expressVo.setLinkUrl("http://www.yitianhealth.com");
        vo.setExpressVo(expressVo);

        msgBean.put("userOrder", vo);

        return msgBean.returnMsg();
    }

    @ApiOperation(value="取消订单", httpMethod = "POST")
    @RequestMapping("/cancel")
    public @ResponseBody  Object cancelOrder(
            @ApiParam("订单ID") @RequestParam(value="id", required = false) Long orderId,
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        UserOrder userOrder = userOrderService.get(orderId);
        if(userOrder == null){
            return msgBean.failure("订单不存在").returnMsg();
        }
        if(userOrder.getUid() != uid){
            return msgBean.failure("非法请求").returnMsg();
        }

        if(Constant.ORDER_STATUS.REFUND.value().equals(userOrder.getOrderStatus())
                || Constant.ORDER_STATUS.CANCEL.value().equals(userOrder.getOrderStatus())){
            return msgBean.failure("当前订单不允许取消操作！").returnMsg();
        }

        if(Constant.ORDER_STATUS.NOT_PAY.value().equals(userOrder.getOrderStatus())){
            userOrderService.updateOrderStatus(orderId, Constant.ORDER_STATUS.CANCEL.value());
        }
        if(Constant.ORDER_STATUS.PAID.value().equals(userOrder.getOrderStatus())){
            userOrderService.updateOrderStatus(orderId, Constant.ORDER_STATUS.CANCEL.value());
            //启动退款
        }

        return msgBean.returnMsg();
    }

    @ApiOperation(value="更改订单付款状态-仅供测试", httpMethod = "POST")
    @RequestMapping("/updateStatus")
    public @ResponseBody  Object cancelOrder(
            @ApiParam("订单号") @RequestParam(value="orderNo", required = false) String orderNo,
            @ApiParam("订单状态：0：未付款，1：已付款") @RequestParam(value="orderStatus", required = false) String orderStatus,
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        if(Config.env.equals("product")){
            return msgBean.failure("非法操作！");
        }
        UserOrder userOrder = userOrderService.getByOrderNo(orderNo);
        if(userOrder == null){
            return msgBean.failure("订单不存在").returnMsg();
        }
        userOrderService.updateOrderStatus(userOrder.getId(), Constant.ORDER_STATUS.PAID.value());

        return msgBean.returnMsg();
    }
}
